<?php

namespace App\Models\Goods;

use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class UserProduct extends Model
{
    use HasDateTimeFormatter;
    protected $table = 'yida_user_products';

    public static function boot()
    {
        parent::boot();
        static::created(function ($userProducts){
            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_insert'=>$userProducts->toArray()];
            Log::channel("LaravelInsert")->error("添加操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"insert",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "添加操作",
                'table' => "yida_user_products"
            ]);
        });
        static::updated(function ($userProducts){
            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_update'=>$userProducts->toArray()];
            Log::channel("LaravelUpdate")->error("更新操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"update",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "更新操作",
                'table' => "yida_user_products"
            ]);
        });
        static::deleted(function ($userProducts){

            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_delete'=>$userProducts->toArray()];
            Log::channel("LaravelDelete")->error("删除操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"delete",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "删除操作",
                'table' => "yida_user_products"
            ]);
        });

    }

    public function user(){
        return $this->belongsTo(User::class,'user_id');
    }

    public static function gen_order_sn($user_id,$product_id) {
        return date('YmdHis').str_pad($user_id,10,'0',STR_PAD_LEFT).str_pad($product_id,10,'0',STR_PAD_LEFT);
    }


    public function product(){
        return $this->belongsTo(Product::class,'product_id');
    }


}
